<?php

namespace app\admin\service\iot\equipment_management;

use app\common\Message;
use app\common\config\iot_device_manage_config\iotDeviceManageConfig;
use app\model\iot_model\IotDevice;
use app\model\iot_model\IotDeviceCategory;
use app\model\iot_model\IotRoom;
use app\model\iot_model\IotStatistic;
use app\model\sync_model\SyncClass;
use app\model\sync_model\SyncMessage;
use app\model\sync_model\SyncMessageDetails;
use app\model\sync_model\SyncOperlog;
use app\model\sync_model\SyncReport;
use app\model\sync_model\SyncUser;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class EquipmentManagementIot
{
    use Message;

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function addRoom($data): bool
    {
        $key = iotDeviceManageConfig::getAddRoomKey();
        foreach($key as $value){
            if(!check_array_key($value,$data)){
                $this->message = '缺少参数！';
                return false;
            }else{
                $insertData[$value] = $data[$value];
            }
        }
        //同一个分组下不能新增同一个功能室
        $where[] = ['company_id','=',$data['company_id']];
        $where[] = ['areas_id','=',$data['areas_id']];
        $where[] = ['unit_id','=',$data['unit_id']];
        $where[] = ['type_id','=',$data['type_id']];
        $where[] = ['name_id','=',$data['name_id']];
        $ret = IotRoom::query()->where($where)->field('id,name_id')->find();
        if(!empty($ret)){
            $this->message = '此分组下已存在新增的功能室！';
            return false;
        }
        unset($insertData['uid']);
        $insertData['create_uid'] = $data['uid'];
        $insertData['create_time'] = time();
        IotRoom::query()->insert($insertData);
        $this->result = 1;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getRoomList($data): bool
    {
        $iotRoom = new IotRoom();

        $where = [
            ['unit_id','=',$data['unit_id']],
        ];
        $list = $iotRoom->where($where)->with(['groupingForName','functionRoomForName'])
            ->field('id,type_id,name_id,unit_id')
            ->select();
        if(count($list)>0){
            $array = [];
            $room_info = [];
            foreach($list as $k=>$v) {
                //分组去重
                if(!in_array_2d($v['name'],$array,'grouping_name')){
                    $array[$k]['grouping_name'] = $v['name'];
                    $array[$k]['grouping_id'] = $v['type_id'];
                    $array[$k]['room_info'] = [];
                }
                $room_info[$k]['type_id'] = $v['type_id'];
                $room_info[$k]['id'] = $v['id'];
                $room_info[$k]['img'] = $v['functionRoomForName']['img'];
                $room_info[$k]['room_name'] = $v['functionRoomForName']['name'];
            }
            $array = array_values($array);
            foreach($array as $k=>$v){
                foreach($room_info as $kk=>$vv){
                    //如果是同一个分类下的功能室放在一起
                    if($v['grouping_id'] == $vv['type_id']){
                        //如果是同一个功能室不添加进来
                        if(!in_array_2d($vv['room_name'],$array[$k]['room_info'],'room_name')){
                            $array[$k]['room_info'][$kk]['room_name'] =$vv['room_name'];
                            $array[$k]['room_info'][$kk]['room_id'] =$vv['id'];
                            $array[$k]['room_info'][$kk]['img'] =$vv['img'];
                            //还需要查询这个房间里的设备数量
                            $array[$k]['room_info'][$kk]['num'] = IotDevice::query()->where('room_id',$vv['id'])->field('id')->count();
                        }
                    }
                }
            }
            foreach($array as $k=>$v){
                $array[$k]['room_info'] = array_values($v['room_info']);
            }
            $this->result = $array;
            $this->message = '操作成功！';
            return true;
        }else{
            $this->result = [];
            $this->message = '操作成功！';
            return true;
        }
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function delRoom($data): bool
    {
        if(empty($data['ids'])){
            $this->message = '缺少参数';
            return false;
        }
        //验证参数是否正确
        $where = [
            ['id','in',$data['ids']],
        ];
        $info = IotRoom::query()->where($where)->field('id')->find();
        if(empty($info)){
            $this->message = '参数错误！';
            return false;
        }
        //查询功能室里是否有设备，有设备的功能室不能直接删除，要先删除里面的设备才能。
        //开始删除
        IotRoom::query()->where($where)->update(['is_del'=>1,'delete_uid'=>$data['uid'],'delete_time'=>time()]);
        $this->result = 1;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getRoomDevice($data): bool
    {
        if(empty($data['id'])){
            $this->message = '缺少参数id';
            return false;
        }
        //验证参数是否正确
        $where = [
            ['id','=',$data['id']],
        ];
        $infos = IotRoom::query()->where($where)->with(['functionRoomForName'])->field('id,type_id,name_id')->find();

        if(empty($infos)){
            $this->message = '参数错误！';
            return false;
        }
        //查询设备数量及在线设备数量
        $devWhere = [
            ['room_id','=',$infos['id']],
        ];
        $deviceInfo = IotDevice::query()->where($devWhere)->field('id,is_online')->select();
        if(count($deviceInfo)>0){
            $devNum = count($deviceInfo);
            $devOnline = 0;
            foreach ($deviceInfo as $value){
                if($value['is_online'] ==1){
                    $devOnline +=1;
                }
            }
        }else{
            $devNum = 0;
            $devOnline = 0;
        }
        $info['name'] = $infos['functionRoomForName']['name'];
        $info['img'] = $infos['functionRoomForName']['img'];
        $info['code'] = $infos['functionRoomForName']['code'];
        $info['remark'] = $infos['functionRoomForName']['remark'];
        $info['devNum'] = $devNum;
        $info['devOnline'] = $devOnline;
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getDeviceCategory($data): bool
    {
        $where = [
            ['is_show','=',1],
        ];
        $ret = IotDeviceCategory::query()->where($where)->field('id,name')->select();
        if(count($ret)>0){
            $this->result = $ret;
            $this->message = '操作成功！';
            return true;
        }else{
            $this->message = '暂无数据，请联系管理员！';
            return false;
        }
    }
    public function categoryConfig($room_id): array
    {
        $data = [
            1 => [
                'name' => '智能身心反馈训练系统',
                'status' => 0
            ],
            2 => [
                'name' => '智能心理自助系统',
                'status' => 0
            ],
            3 => [
                'name' => '智能多维击打呐喊宣泄系统',
                'status' => 0
            ],
            4 => [
                'name' => '智能心语信箱',
                'status' => 0
            ],
            5 => [
                'name' => '身心健康检测仪 ',
                'status' => 0
            ],
        ];
        return $data[$room_id]??[];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function addRoomDevice($data): bool
    {
        $key = iotDeviceManageConfig::getAddDeviceKey();
        foreach ($key as $value){
            if(!check_array_key($value,$data)){
                $this->message = match ($value){
                    'room_id' => '新增的功能室ID不能为空！',
                    'name' => '设备id【关联设备名称】不能为空！',
                    'device_img' => '设备图片不能为空！',
                    'main_components' => '主要构成硬件不能为空！',
                    'secondary_member' => '辅助硬件零件不能为空！',
                    'detailed_parameters' => '设备详细参数不能为空！',
                    'introduce' => '系统介绍不能为空！',
//                    'is_hardware' => '是否非电设备不能为空！'
                };
                return false;
            }else{
                $insertData[$value] = $data[$value];
            }
        }
        $insertData['is_hardware'] = $this->categoryConfig($data['room_id'])['status']??0;
        //验证同一个设备不能同步同样软件
        $where = [
            ['company_id','=',$data['company_id']],
            ['areas_id','=',$data['areas_id']],
            ['unit_id','=',$data['unit_id']],
            ['mac','=',$data['mac']],
            ['name','=',$data['name']],
            ['is_hardware','=',$insertData['is_hardware']],
        ];
        $ret = IotDevice::query()->where($where)->field('id')->find();
        if(!empty($ret)){
            $this->message = '同一个设备不能新增两个一样的软件！';
            return false;
        }
        unset($insertData['uid']);
        $insertData['create_time'] = time();
        $insertData['mac'] = $data['mac'];
        $insertData['company_id'] = $data['company_id'];
        $insertData['areas_id'] = $data['areas_id'];
        $insertData['unit_id'] = $data['unit_id'];
        IotDevice::query()->insert($insertData);
        $this->result = 1;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getDeviceList($data): bool
    {
        if(empty($data['room_id'])){
            $this->message = '缺少参数';
            return false;
        }
        $typeMode = new iotDevice();
        $where = [
            ['room_id','=',$data['room_id']]
        ];
        $field = [
            'id,company_id,areas_id,unit_id,room_id,name,device_img,mac,user_num,end_synchronous_time,is_online,create_time,
            main_components,secondary_member,detailed_parameters,introduce,is_hardware'
        ];
        $count = $typeMode->where($where)->field('id')->count();
        $list = $typeMode->where($where)
            ->with(['deviceForName'])
            ->withCount(['userNum'])
            ->field($field)
            ->page((int)$data['page'], (int)$data['page_size'])
            ->select();
        if(count($list)<=0){
            $list = [];
        }
        $return = ['total' => $count, 'page' => $data['page'], 'page_size' => $data['page_size'],'list' => $list];
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getDeviceAllData($data): bool
    {
        if(empty($data['room_id'])){
            $this->message = '缺少参数';
            return false;
        }
        $where = [
            ['room_id','=',$data['room_id']]
        ];
        $list = IotDevice::query()->where($where)
            ->field('id')
            ->select();
        $this->result = arrayDrop($list->toArray());
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function editDevice($data): bool
    {
        if(empty($data['id'])){
            $this->message = '缺少参数';
            return false;
        }
        $ret = IotDevice::query()->where('id',$data['id'])->field('id')->find();
        if(empty($ret)){
            $this->message = '参数id错误！';
            return false;
        }
        $key = iotDeviceManageConfig::getEditDeviceKey();
        foreach ($key as $value){
            if(!check_array_key($value,$data)){
                $this->message = match ($value){
                    'room_id' => '新增的功能室ID不能为空！',
                    'name' => '设备id【关联设备名称】不能为空！',
                    'device_img' => '设备图片不能为空！',
                    'main_components' => '主要构成硬件不能为空！',
                    'secondary_member' => '辅助硬件零件不能为空！',
                    'detailed_parameters' => '设备详细参数不能为空！',
                    'introduce' => '系统介绍不能为空！',
//                    'is_hardware' => '是否非电设备不能为空！'
                };
                return false;
            }else{
                $updateData[$value] = $data[$value];
            }
        }
        $updateData['is_hardware'] = $this->categoryConfig($ret['room_id'])['status']??0;
        $updateData['update_time'] = time();
        IotDevice::query()->where('id',$data['id'])->update($updateData);
        $this->result = 1;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function delDevice($data): bool
    {
        if(empty($data['ids'])){
            $this->message = '缺少参数';
            return false;
        }
        //如果有同步的内容一起删除了
//        $id = explode(',',$data['ids']);
        //删除设备
        $where = [
            ['id','in',$data['ids']],
        ];
        $info = IotDevice::query()->where($where)->field('id')->find();
        if(empty($info)){
            $this->message = '参数错误！';
            return false;
        }
        $update = [
            'is_del'=>1,
            'update_time'=>time(),
        ];
        $ret = IotDevice::query()->where($where)->update($update);
        if($ret){
            $this->result = 1;
            $this->message = '删除成功！';
            return true;
        }else{
            $this->message = '操作失败,参数错误！';
            return false;
        }
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getDeviceInfo($data): bool
    {
        if(empty($data['id'])){
            $this->message = '缺少参数';
            return false;
        }
        $field = 'name,main_components,device_img,secondary_member,detailed_parameters,is_online,end_synchronous_time,first_synchronous_time,introduce,mac,is_hardware';
        $info = iotDevice::query()->where('id',$data['id'])->with(['deviceForName'])->field($field)->find();
        if(empty($info)){
            $this->message = '缺少参数！暂无数据！';
            return false;
        }
        if($info['end_synchronous_time'] == 0){
            //未同步过一次
            $info['usage_days'] = 0;
        }else{
            //否则等于 现在的时长,减去第一次同步的时长
            $date1 = date_create(date("Y-m-d",time()));
            $date2 = date_create(date("Y-m-d",$info['first_synchronous_time']));
            $diff = date_diff($date1, $date2);
            $info['usage_days'] = $diff->format("%a");
        }
        /*获取用户数据-开始*/
        $where[] = ['device_id','=',$data['id']];
        $temp_field = 'id,device_id,nickname,sex,age,class_id,studentID,username,status,face,fingerprint';
        $userInfo = SyncUser::query()->where($where)->field($temp_field)->select();
        $total = 0;
        $man = 0;
        $woman = 0;
        foreach($userInfo as $value){
            $total += 1;
            switch ($value['sex']){
                case '男':
                    $man += 1;
                    break;
                case '女':
                    $woman += 1;
                    break;
            }
        }
        $info['total'] = $total;
        $info['man'] = $man;
        $info['man_rate'] = $total == 0?0:removeTrailingZero(number_format(($man/$total)*100,1));
        $info['woman'] = $woman;
        $info['woman_rate'] = $total == 0?0:removeTrailingZero(number_format(($woman/$total)*100,1));
        /*获取用户数据-结束*/

        /*获取其他数据-开始*/
        $today = 0;
        $model = []; //模块统计次数
        $model_total_num = 0; //获取模块总点击次数
        // 当天开始时间戳
        $todayStartTimestamp = strtotime("today");
        // 当天结束时间戳
        $todayEndTimestamp = strtotime("tomorrow") - 1;
        $where[] = ['uid','<>',1];
        $otherInfo = SyncOperlog::query()->where($where)->field('uid,title,type,add_time')->select();
        if(count($otherInfo)>0){
            $temp_array = arrayUniqueKey($otherInfo->toArray(),'uid');
            foreach ($temp_array as $value){
                if($value['add_time']>=$todayStartTimestamp && $value['add_time']<=$todayEndTimestamp){
                    //获取当天的数据
                    $today += 1;
                }
            }
            //获取模块总点击次数
            $where[] = ['type','=',1];
            $model_total_num = SyncOperlog::query()->where($where)->field('type')->count();
            //获取每个模块的名称
            $model_array = SyncOperlog::query()->where($where)->field('title')->distinct(true)->select();
            foreach($model_array as $key=>$value){
                $model[$key]['title'] = $value['title'];
                $temp_num = SyncOperlog::query()->where($where)->where('title',$value['title'])->field('title')->count();
                $model[$key]['num'] = $temp_num;
                $model[$key]['num_rate'] = removeTrailingZero(number_format($temp_num/$model_total_num*100,1));
            }
        }
        /*获取其他数据-结束*/
        $info['today'] = $today;
        $info['model_statistics'] = $model;
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getDeviceUsers($data): bool
    {
        if(empty($data['id'])){
            $this->message = '缺少参数';
            return false;
        }
        $searchKey = iotDeviceManageConfig::getDeviceUserListKey();
        foreach($searchKey as $v){
            if (check_array_key($v, $data)){
                switch ($v){
                    case 'name_account':
                        $where[] = ['nickname|username', 'like', '%' . $data[$v] . '%'];
                        break;
                    default:
                        $where[] = [$v,'=',$data[$v]];
                        break;
                }
            }
        }
        $where[] = ['device_id','=',$data['id']];
        $field = 'id,device_id,nickname,sex,age,class_id,studentID,username,status,face,fingerprint';
        $count = SyncUser::query()->where($where)->field('device_id')->count();
        $info = SyncUser::query()->where($where)->page((int)$data['page'], (int)$data['page_size'])->field($field)->select();
        $other['man'] = SyncUser::query()->where($where)->where('sex','=',1)->count();
        $other['woman'] = $count - $other['man'];
        $other['num'] = $count;
        if(count($info)<=0){
            $info = [];
        }else{
            $class_list = SyncClass::query()->where('device_id',$data['id'])->field('id,name,pid')->select();
            foreach($info as $key=>$value){
                $other['num'] += 1;
                switch ($value['sex']){
                    case '1':
                    case '男':
                        $other['man'] += 1;
                        break;
                    case '2':
                    case '女':
                        $other['woman'] += 1;
                        break;
                }
                //获取部门名称
                if(count($class_list)>0){
                    $name = getParents($class_list->toArray(),$value['class_id']);
                    $temp = '';
                    foreach(array_reverse($name) as $v){
                        $temp .= $v['name'];
                    }
                    $info[$key]['class_name'] = $temp;
                }else{
                    $info[$key]['class_name'] = '';
                }
            }
        }
        $return = ['other'=>$other, 'total' => $count,'page' => $data['page'], 'page_size' => $data['page_size'],'list' => $info];
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getClassList($data): bool
    {
        if(empty($data['id'])){
            $this->message = '缺少参数';
            return false;
        }
        $class_list = SyncClass::query()->where('device_id',$data['id'])->field('id,name,pid')->select();
        $class_list = rule_trees($class_list->toArray());
        $this->result = $class_list;
        $this->message = '操作成功！';
        return true;
    }

    public function getUsageRecord($data): bool
    {
        if(empty($data['id'])){
            $this->message = '缺少参数';
            return false;
        }
        $syncHyperLogLog = new SyncOperlog();
        $syncHyperLogLogName = $syncHyperLogLog->getTable();
        $syncUserMode = new SyncUser();
        $syncUserModeName = $syncUserMode->getTable();
        $mode = $syncHyperLogLog::withoutGlobalScope();
        $field = [
            $syncHyperLogLogName .'.UA',$syncHyperLogLogName .'.title',$syncHyperLogLogName.'.type',
            $syncHyperLogLogName .'.uid',$syncHyperLogLogName .'.add_time',
            $syncUserModeName .'.nickname',
        ];
        /*搜索-开始*/
        if (check_array_key('nickname', $data)){
            $where[] = [$syncUserModeName . '.nickname', 'like','%'. $data['nickname']. '%'];
        }
        if (check_array_key('start_time', $data)){
            $where[] = [$syncHyperLogLogName.'.add_time', 'between', [$data['start_time'], $data['end_time']]];
        }
        if (check_array_key('type', $data)){
            $where[] = [$syncHyperLogLogName.'.type', 'in', $data['type']];
        }
        if (check_array_key('time_area', $data)){
            $current_time = strtotime(date('Y-m-d 00:00:00'));
            switch ($data['time_area']){
                case 1:
                    //最近3天
                    $start_time = $current_time - (3 * 24 * 60 * 60);
                    $end_time = $current_time;
                    break;
                case 2:
                    //最近5天
                    $start_time = $current_time - (5 * 24 * 60 * 60); // 开始时间为5天前的0点
                    $end_time = $current_time; // 结束时间为当天0点
                    break;
                default:
                    //最近7天
                    $start_time = $current_time - (7 * 24 * 60 * 60); // 开始时间为7天前的0点
                    $end_time = $current_time; // 结束时间为当天0点
                    break;
            }
            $where[] = [$syncHyperLogLogName.'.add_time', 'between', [$start_time, $end_time]];
        }
        /*搜索-结束*/
        $where[] = [$syncHyperLogLogName .'.device_id','=',$data['id']];
        $where[] = [$syncHyperLogLogName .'.is_del','=',0];
        $mode = $mode
            ->join($syncUserModeName, $syncUserModeName . '.id = ' . $syncHyperLogLogName . '.uid','left');
        $mode = $mode->where($where);
        $count = $mode
            ->field($syncHyperLogLogName.'.device_id')
            ->count();
        $info = $mode
            ->field($field)
            ->page((int)$data['page'], (int)$data['page_size'])
            ->order($syncHyperLogLogName .'.add_time desc')
            ->select();
        if(count($info)<=0){
            $info = [];
        }else{
            foreach($info as $key=>$value){
                if($value['uid'] == 1){
                    $info[$key]['nickname'] = '超级管理员';
                }
            }
        }
        $return = [ 'total' => $count,'page' => $data['page'], 'page_size' => $data['page_size'],'list' => $info];
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getUserDetails($data): bool
    {
        if(empty($data['id'])){
            $this->message = '缺少参数id';
            return false;
        }
        if(empty($data['device_id'])){
            $this->message = '缺少参数device_id';
            return false;
        }
        $where[] = ['device_id','=',$data['device_id']];
        $where[] = ['id','=',$data['id']];
        $field = 'id,device_id,nickname,sex,age,class_id,studentID,username,status,face,fingerprint,uid';
        $info = SyncUser::query()->where($where)->field($field)->find();
        $class_list = SyncClass::query()->where('device_id',$info['device_id'])->field('id,name,pid')->select();
        $name = getParents($class_list->toArray(),$info['class_id']);
        $temp = '';
        foreach(array_reverse($name) as $v){
            $temp .= $v['name'];
        }
        $info['class_name'] = $temp;
        $system_name = IotDevice::query()->where('id',$info['device_id'])->with(['deviceForName'])->field('name')->find();
        $info['dev_name'] = $system_name['dev_name'];
        //获取记录
        $repWhere[] = ['device_id','=',$data['device_id']];
        $repWhere[] = ['uid','=',$info['uid']];
        $report = SyncReport::query()->where($repWhere)->field('*')->order('add_time desc')->select();
        if(count($report)>0){
            $info['report'] = $report;
        }else{
            $info['report'] = [];
        }
        /*获取信箱信息 10；咨询。11.留言,12.倾诉果，13.知识问答,-开始*/
        $messageWhere = [
            ['device_id','=',$data['device_id']],
            ['type','in',[1,2,4,5]],
            ['uid','=',$data['id']],
        ];
        $message = SyncMessage::query()->where($messageWhere)->with(['getSyncUser'])->field('*')->select();
        if(count($message)>0){
            foreach($message as &$item){
                switch ($item['type']){
                    case 1:
                        $item['type'] = 11;
                        break;
                    case 2:
                        $item['type'] = 10;
                        break;
                    case 4:
                        $item['type'] = 12;
                        break;
                    case 5:
                        $item['type'] = 13;
                        break;
                }
            }
            if($info['report']){
                $reports =$info['report']->toArray();
            }else{
                $reports = [];
            }
            $info['report'] = array_merge($reports,$message->toArray());
        }
        /*获取信箱信息 10；咨询。11.留言,12.倾诉果，13.知识问答-结束*/

        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws DbException
     */
    public function audit($data): bool
    {
        $key = ['opinion','rid'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                $this->message = '缺少参数'.$item;
                return false;
            }
        }
        //判断数据是否已经处理过
        $is_ok = SyncMessage::query()->where('rid',$data['rid'])->value('opinion');
        switch ($is_ok){
            case 1:
            case 2:
                $this->message = '此数据已处理';
                return false;
            case 0:
                break;
            default:
                $this->message = '参数rid错误!';
                return false;
        }
        $messageWhere = [
            ['rid','=',$data['rid']],
            ['type','=',2],
        ];
        SyncMessage::query()->where($messageWhere)->update(['opinion'=>$data['opinion'],'status'=>0]);
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getMessageDetails($data): bool
    {
        $messageWhere = [
            ['rid','=',$data['rid']],
        ];
        $list = SyncMessageDetails::query()->where($messageWhere)
            ->page((int)$data['page'], (int)$data['page_size'])
            ->with(['getConsultantName'])
            ->withoutField('is_delete,sync_time,status,device_id')
            ->order('add_time desc')
            ->select();
        $count = SyncMessageDetails::query()->where($messageWhere)->count();
        $result = ['page' => (int)$data['page'], 'page_size' => (int)$data['page_size'], 'total' => $count,'list' => $list];
        $this->result = $result;
        $this->message = '操作成功！';
        return true;
    }

    public function replyMessage($data): bool
    {
        $key = ['content','rid','device_id'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                $this->message = '缺少参数'.$item;
                return false;
            }
        }
        if($data['role_mode'] != 2){
            $this->message = '参数错误，只能咨询师回复！';
            return false;
        }
        $insert['uid'] = $data['uid'];//这里是咨询师ID
        $insert['device_id'] = $data['device_id'];
        $insert['role'] = 1; //别的软件：1咨询师   2用户
        $insert['rid'] = $data['rid'];
        $insert['content'] = $data['content'];
        $insert['add_time'] = time();
        SyncMessageDetails::query()->insert($insert);
        $this->message = '操作成功！';
        return true;
    }

}